package com.api.customization.huangwm.formmode.osahc;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;

import weaver.conn.RecordSet;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;

import com.customization.huangwm.formmode.osahc.OsahcSendMsgUtil;
import com.customization.huangwm.formmode.osahc.SendMsg;
import com.customization.huangwm.utils.DBTools;
import com.customization.huangwm.utils.DateTools;
import com.engine.common.util.ParamUtil;

/**
 * @author Huangwm
 * @package com.api.customization.huangwm.formmode.osahc
 * @description 澳门自来水職安健合同建模页面发起流程
 */
public class OsahcSendMsgApi {
    private Log log = new LogFactory().getLog("custom_huangwm");
    private OsahcSendMsgUtil util = new OsahcSendMsgUtil();
    private SendMsg sendMsg = new SendMsg();
    private DateTools dateTools = new DateTools();
    private DBTools dbTools = new DBTools();

    public String deitail_x = "x";
    public String deitail_mb = "mb";
    public String deitail_hlzb = "hlzb";
    public String deitail_hzgspfjcf = "hzgspfjcf";
    public String deitail_hzgspfjf = "hzgspfjf";
    public String deitail_swyypfjcf = "swyypfjcf";
    public String deitail_swyypfjf = "swyypfjf";
    public String deitail_fzr = "fzr";
    public String deitail_bm = "bm";
    public String deitail_lc = "lc";

    public String main_sfyfstx = "sfyfstx";
    public String main_nf = "nf";
    public String main_txr = "txr";
    public String main_bm = "bm";
    public String main_rq = "rq";
    public String main_fj = "fj";

    @POST
    @Path("/osahcSendMsgApi")
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> Send_Msg(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apiResult = new HashMap<String, Object>();
        log.info("OsahcSendMsgApi--->进入方法");
        try {
            Map<String, Object> requestParams = ParamUtil.request2Map(request);
            log.info(requestParams);
            String billid = "";
            String workflowid = "";
            String maintable = requestParams.get("maintable").toString();
            List<String> detailIndex = Arrays.asList(requestParams.get("detailIndex").toString().split(","));

            if (requestParams.containsKey("billid")) {
                billid = requestParams.get("billid").toString();
                if (billid.equals("")) {
                    apiResult.put("apiStatus", false);
                    apiResult.put("errorCode", "-2");
                    apiResult.put("msg", "参数billid无值,请检查代码块");
                    return apiResult;
                } else {
                    if (requestParams.containsKey("workflowid")) {
                        workflowid = requestParams.get("workflowid").toString();
                        if (workflowid.equals("")) {
                            apiResult.put("apiStatus", false);
                            apiResult.put("errorCode", "-2");
                            apiResult.put("msg", "参数workflowid无值,请检查代码块");
                            return apiResult;
                        } else {
                            log.info(detailIndex);
                            log.info("OsahcSendMsgApi--->参数齐全,开始执行创建流程");

                            int errCounts = 0;
                            int total = 0;
                            List<String> reqList = new ArrayList<>();
                            Map<String, String> mainDatas = util.getMaintableInfo(maintable, billid);
                            String creater = mainDatas.get(main_txr);
                            String createrbm = mainDatas.get(main_bm);
                            String nf = mainDatas.get(main_nf);
                            String createDate = dateTools.getCurrentDate();
                            if (detailIndex.size() > 0) {
                                for (int i = 0; i < detailIndex.size(); i++) {
                                    List<Map<String, String>> detailDatas = util.getDetailtableInfo(maintable, detailIndex.get(i), billid);
                                    if (detailDatas.size() > 0) {
                                        for (int j = 0; j < detailDatas.size(); j++) {
                                            Map<String, String> sendDatas = new HashMap<>();
                                            total++;
                                            sendDatas.put(sendMsg.main_fqr, creater);//发起人
                                            sendDatas.put(sendMsg.main_fqrq, createDate);//发起日期
                                            sendDatas.put(sendMsg.main_nf, nf);//年
                                            sendDatas.put(sendMsg.main_rwmbnr, detailDatas.get(j).get(util.detail_mb));//目标
                                            sendDatas.put(sendMsg.main_tjnr, detailDatas.get(j).get(util.detail_jtgjnr));//跟进内容
                                            sendDatas.put(sendMsg.main_dyctxrq, detailDatas.get(j).get(util.detail_dyctxrq));//第一次提醒日期
                                            sendDatas.put(sendMsg.main_dectxrq, detailDatas.get(j).get(util.detail_dectxrq));//第二次提醒日期
                                            sendDatas.put(sendMsg.main_dsctxrq, detailDatas.get(j).get(util.detail_dsctxrq));//第三次提醒日期
                                            sendDatas.put(sendMsg.main_fzr, detailDatas.get(j).get(util.detail_fzr));//负责人
                                            sendDatas.put(sendMsg.main_fzrbm, detailDatas.get(j).get(util.detail_bm));//负责人部门

                                            String rowid = detailDatas.get(j).get("id");//该行明细的数据库id

                                            try {
                                                RequestInfo requestInfo = sendMsg.setRequestInfo(creater, "職安健合同之跟進項提交表 " + createDate, sendDatas, workflowid);
                                                log.info("检查流程信息" + requestInfo.getCreatorid() + "  " + requestInfo.getWorkflowid());
                                                MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
                                                Property[] properties = mainTableInfo.getProperty();
                                                for (Property property : properties) {
                                                    log.info(property.getName() + ">>>" + property.getValue());
                                                }
                                                log.info("检查流程信息完成");
                                                RequestService service = new RequestService();
                                                String requestid = service.createRequest(requestInfo);
                                                int returnType = Integer.parseInt(requestid);
                                                String msg = "";
                                                if (returnType > 0) {
                                                    reqList.add(requestid);
                                                    //大于0,则创建流程成功
                                                    msg = "流程创建成功:" + requestid;
                                                    RecordSet rs = new RecordSet();
                                                    String sql = "update " + maintable + "_dt" + detailIndex.get(i) + " set lc=" + requestid + ",zt=0 where id=" + rowid;
                                                    log.info("更新明细行的流程字段：" + sql);
                                                    boolean up = rs.execute(sql);
                                                    log.info("更新明细行的流程字段结果：" + up);
                                                } else if (returnType == -1) {
                                                    msg = " 创建流程失败!! ";
                                                } else if (returnType == -2) {
                                                    msg = " 用户没有流程创建权限!! ";
                                                } else if (returnType == -3) {
                                                    msg = "创建流程基本信息失败!! ";
                                                } else if (returnType == -4) {
                                                    msg = "保存表单主表信息失败!! ";
                                                } else if (returnType == -5) {
                                                    msg = "更新紧急程度失败!! ";
                                                } else if (returnType == -6) {
                                                    msg = "流程操作者失败!!";
                                                } else if (returnType == -7) {
                                                    msg = "流转至下一节点失败!! ";
                                                } else if (returnType == -8) {
                                                    msg = "节点附加操作失败!! ";
                                                }
                                                log.info("OsahcSendMsgApi--->detailetable=" + maintable + "_" + detailIndex.get(i) + ",rowid=" + rowid + "   " + msg);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                                log.info("OsahcSendMsgApi--->发起流程异常");
                                                errCounts++;
                                            }
                                        }
                                    }
                                }
                                apiResult.put("apiStatus", true);
                                apiResult.put("errorCode", "1");
                                apiResult.put("requestids", reqList);
                                apiResult.put("total", total);
                                apiResult.put("msg", "发送完成,总共发送" + total + ",其中有" + errCounts + "发送失败(失败原因请联系查看日志" + dateTools.getCurrentTimes() + ")");
                                RecordSet rs2 = new RecordSet();
                                rs2.execute("update " + maintable + " set sfyfstx=1 where id=" + billid);
                            }
                        }
                    } else {
                        apiResult.put("apiStatus", false);
                        apiResult.put("errorCode", "-1");
                        apiResult.put("msg", "缺少参数workflowid,请检查代码块");
                        return apiResult;
                    }
                }
            } else {
                apiResult.put("apiStatus", false);
                apiResult.put("errorCode", "-1");
                apiResult.put("msg", "缺少参数billid,请检查代码块");
                return apiResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
            apiResult.put("apiStatus", false);
            apiResult.put("errorCode", "-3");
            apiResult.put("msg", "程序异常;" + e.getMessage());
            return apiResult;
        }
        log.info("OsahcSendMsgApi--->执行结束");
        return apiResult;
    }
}
